//
//  ClubGameDetailViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/3.
//

import UIKit
import JXSegmentedView

class ClubGameDetailViewController: ClubBaseViewController, RaeAnimationProtocol {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_whiteBack").end()
    private let bgImageview = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let shareButton = c_make_ex(UIButton.self)
        .image("GameDetail_share").end()
    private var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    private var segmentedDataSource = JXSegmentedTitleDataSource()
    private lazy var listContainerView: JXSegmentedListContainerView = {
        return JXSegmentedListContainerView(dataSource: self)
    }()
    private var emptyView = ClubEmptyArticleView()
    
    var gameId: String = "" {
        didSet{
            loadData()
        }
    }
    
    var toForum = false {
        didSet{
            if toForum {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    self.segmentedView.selectItemAt(index: 1)
                }                
            }
        }
    }
    
    private var detailTopModel: ClubGameDetailModel = ClubGameDetailModel()
    private var tagTitles: [String] = []
    private var tagModels: [ClubHomeIndexTopModel] = []
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 移除或隐藏背景图视图
        bgImageview.isHidden = true
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 移除或隐藏背景图视图
        bgImageview.isHidden = false
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            bgImageview
            backButton
            shareButton
            segmentedView
            emptyView
        }
        
        emptyView.isHidden = true
        emptyView.titleString = "当前游戏已下架"
        
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = UIColor.white.alpha(0.5)
        segmentedDataSource.titleSelectedColor = UIColor.white
        segmentedDataSource.titleNormalFont = .systemFont(ofSize: 16.0.Scale, weight: .regular)
        segmentedDataSource.titleSelectedFont = .systemFont(ofSize: 16.0.Scale, weight: .semibold)
        segmentedDataSource.itemSpacing = 11.0.Scale
        segmentedDataSource.isItemSpacingAverageEnabled = false
        segmentedView.dataSource = segmentedDataSource
        
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorColor = .white
        indicator.indicatorHeight = 2.0.Scale
        indicator.indicatorWidth = 28.0.Scale
        indicator.indicatorCornerRadius = 2.0.Scale
        indicator.verticalOffset = 5.0.Scale
        segmentedView.indicators = [indicator]
        
        segmentedView.delegate = self
        segmentedView.backgroundColor = .clear
        
//        listContainerView = JXSegmentedListContainerView(dataSource: self)
        view.addSubview(listContainerView)
        
        segmentedView.listContainer = listContainerView
        
        bgImageview.fillContainer()
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        shareButton.trailing(0).top(.statusHeight).width(48).height(44)
        segmentedView.leading(56).trailing(50).height(44).top(.statusHeight)
        emptyView.leading(0).width(.screenWidth).height(200.0.Scale).top(.navi_height + 160.0.Scale)
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        shareButton.addTarget(self, action: #selector(clickShareButton), for: .touchUpInside)
        
        listContainerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom)
        }
    }
    

    private func loadData(){
        
        Task{
            let res = await self.network.request(.gameTagList(gameID: self.gameId), type: ClubHomeIndexTopModel.self)
                
            if let models = res.models, res.isSuccess {
                self.tagModels.removeAll()
                self.tagTitles.removeAll()
                for m in models {
                    if m.status == true {
                        self.tagTitles.append(m.name)
                        self.tagModels.append(m)
                    }
                }
                self.segmentedDataSource.titles = self.tagTitles
                self.segmentedView.reloadData()
            }
        }
        
        Task{
            let res = await self.network.requestMore(.gameDetailTop(gameID: self.gameId), type: ClubGameDetailModel.self)
            if let model = res.model, res.isSuccess {
                if model.status == "0" {
                    //游戏已经被下架
                    backButton.setImage("Common_blackBack".toImage, for: .normal)
                    shareButton.isHidden = true
                    listContainerView.isHidden = true
                    segmentedView.isHidden = true
                    bgImageview.isHidden = true
                    emptyView.isHidden = false
                }else{
                    
                    backButton.setImage("Common_whiteBack".toImage, for: .normal)
                    shareButton.isHidden = false
                    listContainerView.isHidden = false
                    segmentedView.isHidden = false
                    bgImageview.isHidden = false
                    emptyView.isHidden = true
                }
                self.detailTopModel = model
                self.bgImageview.loadImage(url: model.icon)
                self.bgImageview.addBlurEffectWithOverlay(overlayColor: .black, overlayAlpha: 0.6)
                self.listContainerView.reloadData()
            }
        }

    }
    
    @objc private func clickShareButton(){
        
        let moreView = ClubGameShareView()
        moreView.copyShareBlock = { type in
            self.shareDetail(type: type)
        }
        self.entryAnimate.animation(show: moreView)
    }
    
    private func shareDetail(type: Int) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: self.detailTopModel.name, description: self.detailTopModel.summary, imageUrl: self.detailTopModel.icon, url: self.detailTopModel.fenxiang)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            UIPasteboard.general.string = self.detailTopModel.fenxiang
        }else{
            ClubGlobalTool.shared.shareDetailInfo(title: self.detailTopModel.name, des: self.detailTopModel.summary, imgUrl: self.detailTopModel.icon, shareUrl: self.detailTopModel.fenxiang, shareType: type)
        }
    }
}

extension ClubGameDetailViewController:JXSegmentedListContainerViewDataSource,JXSegmentedViewDelegate {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedDataSource.dataSource.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        //type: 0.游戏 1.论坛 2.工具 3.攻略 4.资讯 5.福利 6.交易
        let type = self.tagModels[index].type
        if type == "1" {
            let forumVC = ClubGameForumViewController()
            forumVC.gameModel = self.detailTopModel
            forumVC.communityId = gameId
            return forumVC
        }else if type == "2" {
            let toolVC = ClubGameDetailToolViewController()
            return toolVC
        }else if type == "3" {
            let strategyVC = ClubGameStrategyViewController()
            strategyVC.gameModel = self.detailTopModel
            strategyVC.communityId = gameId
            return strategyVC
        }else if type == "4" {
            let infoVC = ClubGameInfoViewController()
            infoVC.communityId = gameId
            return infoVC
        }else if type == "5" {
            let welfareVC = ClubGameWelfareViewController()
            welfareVC.gid = gameId
            return welfareVC
        }
//        else if self.tagModels[index].type == "2" {
//            //开服
//            let openVC = ClubOpenServerListViewController()
//            openVC.topModel = self.detailTopModel
//            openVC.gamesID = self.gameId
//            return openVC
//        }
        //self.tagModels[index].type == "0" 游戏详情
        let listVC = ClubGameDetailInfoViewController()
        listVC.topModel = self.detailTopModel    
        listVC.gameId = self.gameId
        return listVC
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
//        if index == 3 {
//            let community = ClubSquareDatailViewController()
//            community.communityId = "96"
//            self.navigationController?.pushViewController(community, animated: true)
//        }
        
    }
    

}

// 一个扩展来将高斯模糊和遮罩效果添加到 UIImageView
extension UIImageView {
    func addBlurEffectWithOverlay(overlayColor: UIColor, overlayAlpha: CGFloat) {
        // 1. 添加高斯模糊效果
        let blurEffect = UIBlurEffect(style: .regular)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.addSubview(blurEffectView)
        
        // 2. 添加遮罩层
        let overlayView = UIView(frame: self.bounds)
        overlayView.backgroundColor = overlayColor
        overlayView.alpha = overlayAlpha
        overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.addSubview(overlayView)
    }
}
